package com.calm.editor.service;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.transaction.annotation.Transactional;

import com.calm.editor.api.BaseService;

@Transactional(readOnly = true)
public abstract class BaseServiceImpl<T, I extends Serializable> implements
		BaseService<T, I> {
	private EntityManager manager;
	@Transactional(readOnly = true)
	public T getById(I id) {
		return manager.find(getEntityClass(), id);
	}

	@Transactional(readOnly = false)
	public void update(T t) {
		manager.merge(t);
	}

	@Transactional(readOnly = false)
	public void save(T t) {
		manager.persist(t);
	}

	public List<T> query(Query<T> q) {
		CriteriaBuilder builder = manager.getCriteriaBuilder();
		CriteriaQuery<T> query = builder.createQuery(getEntityClass());
		Root<T> from = query.from(getEntityClass());
		if (q != null) {
			q.query(builder, query, from);
		}
		TypedQuery<T> createQuery = manager.createQuery(query);
		return createQuery.getResultList();
	}

	public abstract Class<T> getEntityClass();

	@PersistenceContext
	public void setManager(EntityManager manager) {
		this.manager = manager;
	}

}
